<template>
	<div>
		<div class="search">
			<input @focus="changeshow()" @blur="changeshow()" v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
		</div>
		<div class="search-content" ref='search' v-show="on">
			<ul>
				<li class="search-item border-bottom" v-for="item of list" @click="handleCity(item.name)" :key="item.id">{{item.name}}</li>
				<li class="search-item border-bottom" v-show="hide">没有该选项，请检查您的输入内容</li>
			</ul>
		</div>
	</div>
</template>

<script>
	import Bscroll from 'better-scroll'
	/* 实现同步显示搜索内容 */
	export default {
		name: 'CitySearch',
		props: {
			cities: Object
		},
		data() {
			return {
				keyword: '',
				timer: null,
				list: [],
				on: false
			}
		},
		methods: {
			changeshow() {
				this.on = !this.on;
			},
			handleCity(city) {
				this.$store.commit('changeCity', city);
				this.$router.push('/');
			}
		},
		computed: {
			hide() {
				return !this.list.length;
			}
		},
		watch: {
			/* 
				监听输入的内容,当内容改变就去搜索数据
				   再次使用数据节流  防止短时间内多次调用导致浏览器奔溃
			 */
			keyword() {
				if (this.timer) {
					clearTimeout(this.timer);
				}
				/* 当输入框没有内容时,不现实信息 */
				if (!this.keyword) {
					this.list = [];
					return;
				}
				this.timer = setTimeout(() => {
					const result = [];
					for (let i in this.cities) {
						this.cities[i].forEach((value) => {
							if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
								result.push(value);
							}
						})
					}
					this.list = result;
				}, 100)
			}
		},
		mounted() {
			/* 使用第三方滑动包 */
			this.scroll = new Bscroll(this.$refs.search, {
				click: true
			})
		}
	}
</script>

<style lang="less" scoped="scoped">
	@import '~styles/varibles.less';
	[v-cloak] {
		display: none;
	}
	.search {
		height: 0.72rem;
		padding: 0 0.1rem;
		background: @bgcolor;
		.search-input {
			box-sizing: border-box;
			width: 100%;
			height: 0.62rem;
			line-height: 0.62rem;
			text-align: center;
			border-radius: 0.06rem;
			color: #666;
			padding: 0 0.2rem;
		}
	}
	.search-content {
		z-index: 1;
		background: #eee;
		overflow: hidden;
		position: absolute;
		top: 1.58rem;
		left: 0;
		right: 0;
		bottom: 0;
		.search-item {
			line-height: 0.62rem;
			padding-left: 0.2rem;
			color: #666;
			background: #fff;
		}
	}
</style>
